﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using System.IO;
using IFs;
using Imple.Reader;
using Imple.Parse;

namespace Imple.Entities
{
    public class Feed
    {
        private List<Item> _items;

        private Feed()
        {
            _items = new List<Item>();
        }

        public static Feed Subscribe(string uriPath)
        {
            if (string.IsNullOrEmpty(uriPath))
                throw new ArgumentNullException("uriPath");
            Stream stream = DefaultStreamReader.ReadStream(uriPath);

            return ParseInternal(stream);
        }

        public static Feed Subscribe(Stream stream)
        {
            return ParseInternal(stream);
        }

        private static Feed ParseInternal(Stream stream)
        {
            AbstractParser parser = ParserProxy.GetInstance().GetParser(stream);
            parser.TargetStream = stream;

            Feed feed = new Feed();
            ParseTree parseTree = new ParseTree();
            while (parser.ParseNext())
                parseTree.AddNode(parser.CurrentNode);
            if (parser.ValidateTree(parseTree))
                return feed;

            return null;
        }

        internal static IStreamReader DefaultStreamReader
        {
            get { return new XMLStreamReader(); }
        }

        public void Update()
        {

        }

        public ReadOnlyCollection<Item> FeedItems
        {
            get { return _items.AsReadOnly(); }
        }

        public ReadOnlyCollection<Item> UnViewedItems
        {
            get
            {
                List<Item> results = new List<Item>();
                for (int i = 0; i < this._items.Count; i++)
                {
                    if (!_items[i].IsViewed)
                        results.Add(_items[i]);
                }
                return results.AsReadOnly();
            }
        }
    }
}
